<?php

require_once "weixin/WxPay.Api.php";
require_once 'weixin/WxPay.Notify.php';

//初始化日志
// $logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
// $log = Log::Init($logHandler, 15);

class mobileapi_rpc_notify extends WxPayNotify {

    //查询订单
    public function Queryorder($orderid) {
        $input = new WxPayUnifiedOrder();
        $input->SetOut_trade_no($orderid);
        logger::info('微信订单编号:' . print_r($orderid, true) . '.....AlanPi');
        $result = WxPayApi::orderQuery($input);
        logger::info('微信订单查询:' . print_r($result, true) . '.....AlanPi');
//        if (array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS" && $result["trade_state"] == "SUCCESS") {
//            return true;
//        }
        
        if (array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") {
            return true;
        }

        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg) {
        logger::info('微信支付回调:' . var_export($data, true));
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        $data = (array) simplexml_load_string($postStr);
        $notfiyOutput = array();

        if (!array_key_exists("transaction_id", $data)) {
            $msg = "输入参数不正确";
            logger::info($msg);
            return false;
        }

        $is_payed = false;
        //查询订单，判断订单真实性
        if (!$this->Queryorder($data["out_trade_no"])) {
            $msg = "订单查询失败";
            logger::info($msg);
        } else {
            $bill = app::get('ectools')->model('order_bills')->getRow('*', array('bill_id' => $data['out_trade_no']));
            $payment = app::get('ectools')->model('payments')->getRow('*', array('payment_id' => $data['out_trade_no']));
            $sdf = $payment;
            $sdf['orders'][$bill['rel_id']] = $bill;

            $obj_pay_lists = kernel::servicelist("order.pay_finish");

            foreach ($obj_pay_lists as $order_pay_service_object) {
                $is_payed = $order_pay_service_object->order_pay_finish($sdf, 'succ', 'font', $msg);
            }
        }

        return $is_payed;
    }

}

$notify = new mobileapi_rpc_notify();
$notify->Handle(false);
